package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.*;
import cn.topevery.garden.entity.impot.GpsRelateImportParam;
import cn.topevery.garden.entity.po.Car;
import cn.topevery.garden.entity.po.DeviceObjectRelate;
import cn.topevery.garden.entity.po.DeviceObjectRelateList;
import cn.topevery.garden.entity.po.PersonSearch;
import cn.topevery.garden.entity.query.*;
import cn.topevery.garden.entity.vo.DeviceObjectRelateVO;
import cn.topevery.garden.entity.vo.DeviceObjectResultVO;
import cn.topevery.garden.entity.vo.FacilitiesPageVO;
import cn.topevery.garden.entity.vo.GpsDeviceVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.dal.logic.SysDictLogic;
import hw.topevery.basis.entity.fetch.DictFetch;
import hw.topevery.basis.entity.po.SysDict;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备对象关系管理
 *
 * @author code -generate
 * @created 2021 -09-08 14:00:36
 * @date 2021 -09-08
 */
@Api(tags = "设备对象关系接口")
@RestController
@RequestMapping("/deviceObjectRelate")
public class DeviceObjectRelateController extends BaseController {

    /**
     * The Mapper.
     */
    @Autowired
    private Mapper mapper;

    /**
     * The Device object relate logic.
     */
    @Autowired
    private DeviceObjectRelateLogic deviceObjectRelateLogic;

    /**
     * The Device object relate log logic.
     */
    @Autowired
    private DeviceObjectRelateLogLogic deviceObjectRelateLogLogic;

    @Autowired
    private SysDictLogic sysDictLogic;

    /**
     * The Gps device logic.
     */
    @Autowired
    private GpsDeviceLogic gpsDeviceLogic;

    @Autowired
    private PersonLogic personLogic;

    @Autowired
    private CarLogic carLogic;

    @Autowired
    private FacilitiesLogic facilitiesLogic;

    /**
     * 设备对象关系-列表
     *
     * @param query the query
     * @return json result
     * @author wenzhao.lin
     * @created 2021 -09-08 14:00:36 List page json result.
     */
    @ApiOperation(value = "获取设备对象关系列表")
    @GetMapping("/listPage")
    public JsonResult<DataPager<DeviceObjectRelate>> listPage(DeviceObjectRelateQuery query) {
        return JsonResult.ok(deviceObjectRelateLogic.listPage(query));
    }

    @ApiOperation(value = "获取设备对象关系列表")
    @PostMapping("/add")
    public JsonResult<?> add(@RequestBody DeviceObjectRelateVO deviceObjectRelateVO) {
        DictFetch para = new DictFetch();
        para.setNsId("BEE08094-C544-4B27-A740-DF96B0A8428D");
        List<SysDict> sysDictList = sysDictLogic.getListDict(para);
        deviceObjectRelateDataCheck(deviceObjectRelateVO,sysDictList);
        if(deviceObjectRelateVO.isPass()){
            saveImportData(deviceObjectRelateVO,sysDictList);
            return JsonResult.ok();
        }
        else{
            return JsonResult.error(deviceObjectRelateVO.getAnalysisRes());
        }
    }

    /**
     * 描述 设备对象关系-新增/编辑.
     *
     * @param list the list
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-08 14:00:36 Save or update json result.
     */
    @ApiOperation("新增/编辑 设备对象关系信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody DeviceObjectRelateList list) {
        if (list.getDeviceObjectRelateList() != null) {
            for (DeviceObjectRelate deviceObjectRelate : list.getDeviceObjectRelateList()) {
                deviceObjectRelateLogic.saveOrUpdate(getUser().id.toString(), deviceObjectRelate);

                deviceObjectRelateLogLogic.saveOrUpdate(getUser().id.toString(), deviceObjectRelate, 2);
            }
        }
        return JsonResult.ok(true);
    }

    /**
     * 描述 设备对象关系-详情
     *
     * @param id the id
     * @return the info by id
     * @author wenzhao.lin
     * @created 2021 -09-08 14:00:36
     */
    @ApiOperation("通过Id获取设备对象关系详情")
    @GetMapping("/getInfoById")
    public JsonResult<DeviceObjectRelate> getInfoById(@RequestParam Integer id) {
        DeviceObjectRelate entity = deviceObjectRelateLogic.getEntity(id);
        DeviceObjectRelate vo = mapper.map(entity, DeviceObjectRelate.class);
        return JsonResult.ok(vo);
    }

    /**
     * 描述 设备对象关系-批量删除
     *
     * @param list the list
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-08 14:00:36 Delete batch by id json result.
     */
    @ApiOperation("根据自增ID批量删除设备对象关系")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@Valid @RequestBody DeviceObjectRelateList list) {
        if (list.getDeviceObjectRelateList() != null) {
            for (DeviceObjectRelate deviceObjectRelate : list.getDeviceObjectRelateList()) {
                deviceObjectRelateLogic.deleteById(deviceObjectRelate.getDeviceId(), deviceObjectRelate.getObjectId());

                deviceObjectRelateLogLogic.saveOrUpdate(getUser().id.toString(), deviceObjectRelate, 3);
            }
        }
        return JsonResult.ok(true);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @ApiOperation("检查导入数据")
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<DeviceObjectRelateVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, DeviceObjectRelateVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }
        DictFetch para = new DictFetch();
        para.setNsId("BEE08094-C544-4B27-A740-DF96B0A8428D");
        List<SysDict> sysDictList = sysDictLogic.getListDict(para);

        List<DeviceObjectRelateVO> newData = new ArrayList<>();
        for (DeviceObjectRelateVO p : persons) {
            if (p.getSid() == 0 && p.getCode() == null) {
                break;
            }
            deviceObjectRelateDataCheck(p,sysDictList);
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 设备数据检查
     *@param
     *@返回值
     *@创建人  peng.tian
     *@创建时间  2021/9/13
     */
    private void deviceObjectRelateDataCheck(DeviceObjectRelateVO p,List<SysDict> sysDictList) {
        String anaylsisRes = "";
        SysDict sysDict = null;
        if(StringUtils.isNotBlank(p.getObjectTypeName())) {
            for (SysDict temp: sysDictList) {
                if(temp.dictName.equals(p.getObjectTypeName())){
                    sysDict = temp;
                }
            }
            //sysDict=sysDictList.stream().filter(f -> f.dictName.equals(p.getObjectTypeName())).findFirst().get();
        }
        if(p.getObjectType()!=null)
        {
            sysDict=sysDictList.stream().filter(f -> f.dictCode.equals(p.getObjectType().toString())).findFirst().get();
        }
        if (sysDict == null) {
            anaylsisRes = "设备编号为：" + p.getCode() + " 的设备类型: " + p.getObjectTypeName() + " 未找到；";
        } else {

            GpsDeviceQuery query = new GpsDeviceQuery();
            query.setCode(p.getCode());
            DataPager<GpsDeviceVO> page = gpsDeviceLogic.listPage(query);
            if (page.records != null && page.records.size() > 0) {
                p.setDeviceId(page.records.get(0).getId());
                boolean isExists = deviceObjectRelateLogic.isExit("c_device_id", String.valueOf(page.records.get(0).getId()), sysDict.dictCode);
                if (isExists) {
                    anaylsisRes += "设备编号为：" + p.getCode() + " 的设备已被同类型使用，请更换设备；";
                } else {
                    switch (sysDict.dictCode) {
                        case "0":
                            anaylsisRes = importPersonCheck(sysDict, p);
                            break;
                        case "1":
                            anaylsisRes = importCarCheck(sysDict, p);
                            break;
//                            case "7":
//                                anaylsisRes = importTrashOverflowCheck(sysDict, p);
//                                break;
//                            case "8":
//                                anaylsisRes = importManholeCoverCheck(sysDict, p);
//                                break;
//                            default:
//                                anaylsisRes = "设备编号为：" + p.getCode() + " 的设备类型: " + p.getObjectTypeName() + " 暂不支持导入；";
//                                break;
                        default:
                            anaylsisRes = importCommonFacilitiesCheck(sysDict, p);
                            break;
                    }
                }
            } else {
                anaylsisRes += "设备编号为：" + p.getCode() + " 的设备不存在，请更换设备；";
            }
        }


        if (anaylsisRes.length() > 0) {
            p.setPass(false);
            p.setAnalysisRes(anaylsisRes);
        } else {
            p.setPass(true);
            p.setAnalysisRes("验证通过");
        }
    }

    private String importCarCheck(SysDict sysDict, DeviceObjectRelateVO p) {
        String anaylsisRes = "";

        CarQuery query = new CarQuery();
        query.setName(p.getObjectName());
        DataPager<Car> page = carLogic.listPage(query);
        if (page.records != null && page.records.size() > 0) {
            p.setObjectId(page.records.get(0).getId());
            boolean isExists2 = deviceObjectRelateLogic.isExit("c_object_id", String.valueOf(page.records.get(0).getId()), sysDict.dictCode);
            if (isExists2) {
                anaylsisRes = "车辆：" + p.getObjectName() + " 已有设备，请先回收此车辆的设备；";
            }
        } else {
            anaylsisRes = "车辆：" + p.getObjectName() + " 不存在，请确定确保人员已在存在系统中；";
        }
        return anaylsisRes;
    }

    /**
     * 井盖设备检查
     *
     * @param
     * @返回值
     * @创建人 peng.tian
     * @创建时间 2021/9/11
     */
    private String importManholeCoverCheck(SysDict sysDict, DeviceObjectRelateVO p) {
        String anaylsisRes = "";

        if (!importFacilitiesCheck(p)) {
            anaylsisRes = "井盖：" + p.getObjectName() + " 不存在，请确定该设施已存在系统中；";
        }

        return anaylsisRes;
    }

    /**
     * 垃圾桶满溢设备检查
     *
     * @param
     * @返回值
     * @创建人 peng.tian
     * @创建时间 2021/9/11
     */
    private String importTrashOverflowCheck(SysDict sysDict, DeviceObjectRelateVO p) {
        String anaylsisRes = "";

        if (!importFacilitiesCheck(p)) {
            anaylsisRes = "垃圾桶满溢：" + p.getObjectName() + " 不存在，请确定该设施已存在系统中；";
        }

        return anaylsisRes;
    }

    private boolean importFacilitiesCheck(DeviceObjectRelateVO p) {
        FacilitiesQuery query = new FacilitiesQuery();
        query.setName(p.getObjectName());

        DataPager<FacilitiesPageVO> page = facilitiesLogic.listPage(query);
        if (page.records != null && page.records.size() > 0) {
            p.setObjectId(page.records.get(0).getId());
            return true;
        } else {
            return false;
        }
    }

    private String importCommonFacilitiesCheck(SysDict sysDict, DeviceObjectRelateVO p) {
        String anaylsisRes = "";

        if (!importFacilitiesCheck(p)) {
            anaylsisRes = sysDict.dictName + "：" + p.getObjectName() + " 不存在，请确定该设施已存在系统中；";
        }

        return anaylsisRes;
    }

    private String importPersonCheck(SysDict sysDict, DeviceObjectRelateVO p) {
        String anaylsisRes = "";

        PersonQuery query2 = new PersonQuery();
        query2.setName(p.getObjectName());
        DataPager<PersonSearch> page2 = personLogic.listPage(query2);
        if (page2.records != null && page2.records.size() > 0) {
            p.setObjectId(page2.records.get(0).getId());
            boolean isExists2 = deviceObjectRelateLogic.isExit("c_object_id", String.valueOf(page2.records.get(0).getId()), sysDict.dictCode);
            if (isExists2) {
                anaylsisRes = "人员：" + p.getObjectName() + " 已有设备，请先回收此人员的设备；";
            }
        } else {
            anaylsisRes = "人员：" + p.getObjectName() + " 不存在，请确定确保人员已在存在系统中；";
        }
        return anaylsisRes;
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @ApiOperation("导入数据")
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody GpsRelateImportParam param) {
        if (param.getTableData() != null && param.getTableData().size() > 0) {
            DictFetch para = new DictFetch();
            para.setNsId("BEE08094-C544-4B27-A740-DF96B0A8428D");
            List<SysDict> sysDictList = sysDictLogic.getListDict(para);
            for (DeviceObjectRelateVO p : param.getTableData()) {
                saveImportData(p,sysDictList);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }

    private void saveImportData(DeviceObjectRelateVO p,List<SysDict> sysDictList) {
        DeviceObjectRelate tmp = new DeviceObjectRelate();
        tmp.setCode(p.getCode());
        tmp.setDeviceId(p.getDeviceId());
        tmp.setObjectId(p.getObjectId());
        if(StringUtils.isNotBlank(p.getObjectTypeName())) {
            tmp.setObjectType(Integer.parseInt(sysDictList.stream().filter(f -> f.dictName.equals(p.getObjectTypeName())).findFirst().get().dictCode));
        }
        else{
            tmp.setObjectType(Integer.parseInt(sysDictList.stream().filter(f -> f.dictCode.equals(p.getObjectType().toString())).findFirst().get().dictCode));
        }
        deviceObjectRelateLogic.saveOrUpdate(getUser().id.toString(), tmp);
        deviceObjectRelateLogLogic.saveOrUpdate(getUser().id.toString(), tmp, 2);
    }

    /**
     * 获取没有被匹配的设备列表
     *
     * @param query the query
     * @return dps list
     * @author wenzhao.lin
     * @created 2021 -09-08 14:00:36
     */
    @ApiOperation(value = "获取没有被匹配的设备列表")
    @PostMapping("/getDpsList")
    public JsonResult<DataPager<GpsDeviceVO>> getDpsList(@RequestBody GpsDeviceQuery query) {

        List<DeviceObjectRelate> list = deviceObjectRelateLogic.getAllList(query.getDeviceType());

        List<Integer> ids = new ArrayList<>();
        for (DeviceObjectRelate deviceObjectRelate : list) {
            ids.add(deviceObjectRelate.getDeviceId());
        }

        query.setIdList(ids);
        DataPager<GpsDeviceVO> page = gpsDeviceLogic.listPage(query);

        return JsonResult.ok(page);
    }

    /**
     * 描述 获取人员、车辆列表
     *
     * @param query the query
     * @return the data list
     * @author wenzhao.lin
     * @created 2021 -09-08 14:59:14
     */
    @ApiOperation(value = "获取人员、车辆列表")
    @PostMapping("/getDataList")
    public JsonResult<DataPager<DeviceObjectResultVO>> getDataList(@RequestBody DeviceObjectResultQuery query) {
        DataPager<DeviceObjectResultVO> page = deviceObjectRelateLogic.getDataPage(query);
        return JsonResult.ok(page);
    }
}
